package com.woniuxy.qiantai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.qiantai.entity.*;
import com.woniuxy.qiantai.mapper.*;
import com.woniuxy.qiantai.service.CartitemService;
import com.woniuxy.qiantai.service.OrderService;
import com.woniuxy.qiantai.vo.OrderItemVo;
import com.woniuxy.qiantai.vo.OrderVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author firstGroup
 * @since 2023-02-22 09:45:58
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private CartitemService cartitemService;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    RedisTemplate<String, Object> stringObjectRedisTemplate;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderitemMapper orderitemMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    AddressMapper addressMapper;



    //注入模板
    @Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }


    @Override
    @Transactional
    public void createOrder(Integer[] productIds, Integer addressId, Integer userId) {
        //根据商品id从购物车查询出商品数量和总价
        List<Cartitem> cartitems = cartitemService.createOrderPreview(productIds, userId).getCartitemList();
        //根据选中商品的所属店铺进行分组
        Set<Integer> shopNumber = new HashSet<>();
        for (Cartitem cartitem : cartitems) {
            shopNumber.add(cartitem.getShopId());
        }

        for (Integer shopId : shopNumber) {
            //计算每个分组的价格
            BigDecimal totalPrice = new BigDecimal(0.00);
            for (Cartitem cartitem : cartitems) {
                if (shopId == cartitem.getShopId()) {
                    totalPrice = cartitem.getSumPrice().add(totalPrice);
                }
            }
            //根据分组 生成每个分组对应的主订单
            Order order = new Order();
            order.setUserId(userId);
            order.setAddressId(addressId);
            order.setShopId(shopId);
            order.setCreateTime(new Date());
            order.setSumPrice(totalPrice);
            order.setStatus(0);
            orderMapper.insert(order);
            //生成订单分项对应的订单详情
            for (Cartitem cartitem : cartitems) {
                if (shopId == cartitem.getShopId()) {
                    Orderitem orderitem = new Orderitem();
                    orderitem.setUserId(userId);
                    orderitem.setProductId(cartitem.getProductId());
                    orderitem.setPrice(cartitem.getProductPrice());
                    orderitem.setCount(cartitem.getCount().intValue());
                    orderitem.setId(order.getId());
                    orderitem.setOrderId(order.getId());
                    orderitem.setStutus(0);
                    orderitem.setShopId(shopId);
                    orderitemMapper.insert(orderitem);
                }
            }
            //订单创建完成，将订单id发送给业务交换机（实现延迟支持自动取消订单）
            rabbitTemplate.convertAndSend("userNormalExchange","userNormalRouting",order.getId());
        }
        //下单完成需要在清楚在购物车中的记录
        for (Integer productId : productIds) {
            stringObjectRedisTemplate.opsForHash().delete(String.valueOf(userId),String.valueOf(productId));
        }

    }

    //商家生产者
    @Override
    public void expenditure(Integer orderId) {
        rabbitTemplate.convertAndSend("MercantileNormalExchange", "MercantileNormalRouting", orderId);
    }


    //张朝朝：发送到普通交换机，普通交换机发送到普通队列，普通队列延时发送到死信交换机，然后发送到死信队列，消费者接收死信队列消息
    @Override
    public void sendMessageToDelayQueue(Integer orderId) {
        //生产者将消息发送到普通交换机
        rabbitTemplate.convertAndSend("userNormalExchange", "userNormalRouting", orderId);

    }

    //张朝朝：通过orderId立即修改订单状态
    @Override
    public void updateOrderState(Integer orderId, Integer state) {
        //通过订单id获取订单信息
        System.out.println("orderId:" + orderId);
        Order order = orderMapper.selectById(orderId);
        //产看订单状态
        System.out.println("order类型：" + order.getStatus());
        Integer status = order.getStatus();
        System.out.println("未修改前的订单状态:" + status);
        //更新订单状态
        order.setStatus(state);
        int updateById = orderMapper.updateById(order);
        System.out.println("更新订单状态updateById:" + updateById);
    }

    @Override
    public List<OrderVo> selectOrderVo(Integer userId) {
      /*  List<Order> orderList = orderMapper.selectList(null);
        List<Orderitem> orderitems = orderitemMapper.selectList(null);
        System.out.println(orderList);
        System.out.println(orderitems);*/
      //根据userid查询出用户的所有订单
        QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Order> orderList = orderMapper.selectList(queryWrapper.orderByDesc("id"));

        //创建一个集合 存储所有订单 和订单对应的详情订单
        List<OrderVo> orderVoList=new ArrayList<>();
        for (Order order : orderList) {
            //将Order对象封装成OrderVo对象
            OrderVo orderVo = new OrderVo();
            orderVo.setId(order.getId());
            Shop shop = shopMapper.selectById(order.getShopId());
            orderVo.setShopName(shop.getName());
            Address address = addressMapper.selectById(order.getAddressId());
            orderVo.setAddressName(address.getAddress());
            orderVo.setCreateTime(order.getCreateTime());
            orderVo.setSumPrice(order.getSumPrice());
            orderVo.setStatus(order.getStatus());
            orderVo.setProductImgSrc(shop.getImgSrc());
            orderVo.setReceiveName(address.getReceiveName());
            orderVo.setTel(address.getTel());
            //根据orderId 查询出对应的订单详情
            QueryWrapper<Orderitem> orderitemQueryWrapper=new QueryWrapper<>();
            orderitemQueryWrapper.eq("order_id",order.getId()).and(new Consumer<QueryWrapper<Orderitem>>() {
                @Override
                public void accept(QueryWrapper<Orderitem> orderitemQueryWrapper) {
                    orderitemQueryWrapper.eq("user_id",userId);
                }
            });
            List<Orderitem> orderitems = orderitemMapper.selectList(orderitemQueryWrapper);
            //将Orderitem集合封装成OrderItemVo集合
            List<OrderItemVo> orderItemVoList=new ArrayList<>();
            for (Orderitem orderitem : orderitems) {
                //将Orderitem对象封装成OrderItemVo对象
                OrderItemVo orderItemVo = new OrderItemVo();
                Product product = productMapper.selectById(orderitem.getProductId());
                orderItemVo.setProductName(product.getName());
                orderItemVo.setProductImgSrc(product.getImgSrc());
                orderItemVo.setId(orderitem.getId());
                orderItemVo.setUserId(orderitem.getUserId());
                orderItemVo.setProductId(orderitem.getProductId());
                orderItemVo.setPrice(orderitem.getPrice());
                orderItemVo.setCount(orderitem.getCount());
                orderItemVo.setOrderId(orderitem.getOrderId());
                orderItemVo.setStutus(orderitem.getStutus());
                orderItemVo.setShopId(orderitem.getShopId());
                //将OrderItemVo对象加入集合
                orderItemVoList.add(orderItemVo);
            }
            orderVo.setOrderItemVoList(orderItemVoList);
            orderVoList.add(orderVo);
        }
        return orderVoList;
    }

    @Override
    public Page<OrderVo> pageOrderVolist(Integer userId, Integer pageSize, Integer currentPage) {
        Page<Order> orderPage = new Page<>(currentPage, pageSize);
        Page<OrderVo> orderVoPage = new Page<>(currentPage, pageSize);
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Page<Order> orderPage1 = orderMapper.selectPage(orderPage, queryWrapper.orderByDesc("id"));
        List<Order> orderList = orderPage1.getRecords();
        //创建一个集合 存储所有订单 和订单对应的详情订单
        List<OrderVo> orderVoList = new ArrayList<>();
        for (Order order : orderList) {
            //将Order对象封装成OrderVo对象
            OrderVo orderVo = new OrderVo();
            orderVo.setId(order.getId());
            Shop shop = shopMapper.selectById(order.getShopId());
            orderVo.setShopName(shop.getName());
            Address address = addressMapper.selectById(order.getAddressId());
            orderVo.setAddressName(address.getAddress());
            orderVo.setCreateTime(order.getCreateTime());
            orderVo.setSumPrice(order.getSumPrice());
            orderVo.setStatus(order.getStatus());
            orderVo.setProductImgSrc(shop.getImgSrc());
            orderVo.setReceiveName(address.getReceiveName());
            orderVo.setTel(address.getTel());
            //根据orderId 查询出对应的订单详情
            QueryWrapper<Orderitem> orderitemQueryWrapper = new QueryWrapper<>();
            orderitemQueryWrapper.eq("order_id", order.getId()).and(new Consumer<QueryWrapper<Orderitem>>() {
                @Override
                public void accept(QueryWrapper<Orderitem> orderitemQueryWrapper) {
                    orderitemQueryWrapper.eq("user_id", userId);
                }
            });
            List<Orderitem> orderitems = orderitemMapper.selectList(orderitemQueryWrapper);
            //将Orderitem集合封装成OrderItemVo集合
            List<OrderItemVo> orderItemVoList = new ArrayList<>();
            for (Orderitem orderitem : orderitems) {
                //将Orderitem对象封装成OrderItemVo对象
                OrderItemVo orderItemVo = new OrderItemVo();
                Product product = productMapper.selectById(orderitem.getProductId());
                orderItemVo.setProductName(product.getName());
                orderItemVo.setProductImgSrc(product.getImgSrc());
                orderItemVo.setId(orderitem.getId());
                orderItemVo.setUserId(orderitem.getUserId());
                orderItemVo.setProductId(orderitem.getProductId());
                orderItemVo.setPrice(orderitem.getPrice());
                orderItemVo.setCount(orderitem.getCount());
                orderItemVo.setOrderId(orderitem.getOrderId());
                orderItemVo.setStutus(orderitem.getStutus());
                orderItemVo.setShopId(orderitem.getShopId());
                //将OrderItemVo对象加入集合
                orderItemVoList.add(orderItemVo);
            }
            orderVo.setOrderItemVoList(orderItemVoList);
            orderVoList.add(orderVo);
        }
        orderVoPage.setTotal(orderPage.getTotal());
        orderVoPage.setPages(orderPage.getPages());
        orderVoPage.setRecords(orderVoList);

        return orderVoPage;
    }

    @Override
    public Order selectOrderInfo(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        return order;
    }

    //给商家发送订单邮件
    @Override
    public void sendOrderEmail(Integer orderId) {
        rabbitTemplate.convertAndSend("OrderEmailExchange", "OrderEmail", orderId);
    }

}

